<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#fff">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
      
    
    
      
    
  <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "b3c7d22e"
    });
  daovoice('update');
  </script>








  <meta name="baidu-site-verification" content="true" />







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="mask-icon" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1" color="#fff">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"perspectiveLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"perspectiveLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键字","hits_empty":"没有找到与 ${query} 相关的内容","hits_stats":"${hits}条相关记录，共耗时${time} ms"}
    }
  };
</script>


  



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://yfzhou.coding.me/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>

  <meta name="description" content="最烦面试官问，“为什么XX算法的时间复杂度是OO”，今后，不再惧怕这类问题">
<meta name="keywords" content="时间复杂度,算法">
<meta property="og:type" content="article">
<meta property="og:title" content="拜托，面试别再问我时间复杂度了！！！">
<meta property="og:url" content="https://yfzhou.coding.me/2018/10/11/拜托，面试别再问我时间复杂度了！！！/index.html">
<meta property="og:site_name" content="Felix">
<meta property="og:description" content="最烦面试官问，“为什么XX算法的时间复杂度是OO”，今后，不再惧怕这类问题">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://mp.weixin.qq.com/mp/qrcode?scene=10000004&size=102&__biz=MjM5ODYxMDA5OQ==&mid=2651961431&idx=1&sn=4f46fbada3d99ca6cf74b305d06c1ac6&send_time=">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189487005_0.png">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189487781_1.png">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189488546_2.png">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189489295_3.png">
<meta property="og:updated_time" content="2019-04-17T08:59:25.258Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="拜托，面试别再问我时间复杂度了！！！">
<meta name="twitter:description" content="最烦面试官问，“为什么XX算法的时间复杂度是OO”，今后，不再惧怕这类问题">
<meta name="twitter:image" content="https://mp.weixin.qq.com/mp/qrcode?scene=10000004&size=102&__biz=MjM5ODYxMDA5OQ==&mid=2651961431&idx=1&sn=4f46fbada3d99ca6cf74b305d06c1ac6&send_time=">



  <link rel="alternate" href="/atom.xml" title="Felix" type="application/atom+xml" />




  <link rel="canonical" href="https://yfzhou.coding.me/2018/10/11/拜托，面试别再问我时间复杂度了！！！/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>拜托，面试别再问我时间复杂度了！！！ | Felix</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Felix</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">Viva La Vida</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />TopX</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="输入关键字搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yfzhou.coding.me/2018/10/11/拜托，面试别再问我时间复杂度了！！！/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Felix">
      <meta itemprop="description" content="周宇峰的博客">
      <meta itemprop="image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Felix">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">拜托，面试别再问我时间复杂度了！！！
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-11 17:42:32" itemprop="dateCreated datePublished" datetime="2018-10-11T17:42:32+08:00">2018-10-11</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-17 16:59:25" itemprop="dateModified" datetime="2019-04-17T16:59:25+08:00">2019-04-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/" itemprop="url" rel="index"><span itemprop="name">算法</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/10/11/拜托，面试别再问我时间复杂度了！！！/" class="leancloud_visitors" data-flag-title="拜托，面试别再问我时间复杂度了！！！">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-edit"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">4.7k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">6 分钟</span>
              
            </div>
          

          
              <div class="post-description">最烦面试官问，“为什么XX算法的时间复杂度是OO”，今后，不再惧怕这类问题</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><span></span></p>
<a id="more"></a>
<p>此文摘自微信公众号【架构师之路】</p>
<center>微信扫一扫<br>关注该公众号</center>

<p><img src="https://mp.weixin.qq.com/mp/qrcode?scene=10000004&amp;size=102&amp;__biz=MjM5ODYxMDA5OQ==&amp;mid=2651961431&amp;idx=1&amp;sn=4f46fbada3d99ca6cf74b305d06c1ac6&amp;send_time=" alt=""></p>
<p>快速排序分为这么几步：</p>
<p><strong>第一步</strong>，先做一次partition；</p>
<p><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189487005_0.png" alt=""> </p>
<p>partition使用第一个元素t=arr[low]为哨兵，把数组分成了两个半区：</p>
<ul>
<li><p>左半区比t大</p>
</li>
<li><p>右半区比t小</p>
</li>
</ul>
<p><strong>第二步</strong>，左半区递归；</p>
<p><strong>第三步</strong>，右半区递归；</p>
<p>伪代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">void quick_sort(int[]arr, int low, int high)&#123;</span><br><span class="line">         if(low== high) return;</span><br><span class="line">         int i = partition(arr, low, high);</span><br><span class="line">         quick_sort(arr, low, i-1);</span><br><span class="line">         quick_sort(arr, i+1, high);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>为啥，快速排序，时间复杂度是O(n*lg(n))呢？</strong></p>
<p>今天和大家聊聊时间复杂度。</p>
<p><em>画外音：往下看，第三类方法很牛逼。</em></p>
<p><strong>第一大类，简单规则</strong></p>
<p>为方便记忆，先总结几条简单规则，热热身。</p>
<p>规则一：“有限次操作”的时间复杂度往往是O(1)。</p>
<p><strong>例子：交换两个数a和b的值。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">void swap(int&amp; a, int&amp; b)&#123;</span><br><span class="line"></span><br><span class="line">         int t=a;</span><br><span class="line"></span><br><span class="line">         a=b;</span><br><span class="line"></span><br><span class="line">         b=t;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>分析</strong>：通过了一个中间变量t，进行了3次操作，交换了a和b的值，swap的时间复杂度是O(1)。</p>
<p><em>画外音：这里的有限次操作，是指不随数据量的增加，操作次数增加。</em></p>
<p>规则二：“for循环”的时间复杂度往往是O(n)。</p>
<p><strong>例子：n个数中找到最大值。</strong></p>
<figure class="highlight plain"><figcaption><span>max(int[] arr, int n)&#123;</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">         int temp = -MAX;</span><br><span class="line"></span><br><span class="line">         for(int i=0;i&lt;n;++i)</span><br><span class="line"></span><br><span class="line">                   if(arr[i]&gt;temp) temp=arr[i];</span><br><span class="line"></span><br><span class="line">         return temp;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>分析</strong>：通过一个for循环，将数据集遍历，每次遍历，都只执行“有限次操作”，计算的总次数，和输入数据量n呈<strong>线性关系</strong>。</p>
<p>规则三：“树的高度”的时间复杂度往往是O(lg(n))。</p>
<p><strong>分析</strong>：树的总节点个数是n，则树的高度是lg(n)。</p>
<p>在一棵包含n个元素二分查找树上进行<strong>二分查找</strong>，其时间复杂度是O(lg(n))。</p>
<p>对一个包含n个元素的堆顶元素弹出后，<strong>调整成一个新的堆</strong>，其时间复杂度也是O(lg(n))。</p>
<p><strong>第二大类：组合规则</strong></p>
<p>通过简单规则的时间复杂度，来求解组合规则的时间复杂度。</p>
<p><strong>例如：n个数冒泡排序。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">void bubble_sort(int[] arr, int n)&#123;</span><br><span class="line"></span><br><span class="line">   for(int i=0;i&lt;n;i++)</span><br><span class="line"></span><br><span class="line">       for(int j=0;j&lt;n-i-1;j++)</span><br><span class="line"></span><br><span class="line">           if(arr[j]&gt;arr[j+1])</span><br><span class="line"></span><br><span class="line">                swap(arr[j], arr[j+1]);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>分析</strong>：冒泡排序，可以看成三个规则的组合：</p>
<p>1. 外层for循环</p>
<p>2. 内层for循环</p>
<p>3. 最内层的swap</p>
<p>故，<strong>冒泡排序</strong>的时间复杂度为：</p>
<p>O(n) <em> O(n) </em> O(1) = O(n^2)</p>
<p><strong>又例如：TopK问题，通过建立k元素的堆，来从n个数中求解最大的k个数。</strong></p>
<p><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189487781_1.png" alt=""> </p>
<p>先用前k个元素生成一个小顶堆，这个小顶堆用于存储，当前最大的k个元素。</p>
<p><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189488546_2.png" alt=""> </p>
<p>接着，从第k+1个元素开始扫描，和堆顶（堆中最小的元素）比较，如果被扫描的元素大于堆顶，则替换堆顶的元素，并调整堆，以保证堆内的k个元素，总是当前最大的k个元素。</p>
<p><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/1540189489295_3.png" alt=""> </p>
<p>直到，扫描完所有n-k个元素，最终堆中的k个元素，就是为所求的TopK。</p>
<p><strong>伪代码</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">heap[k] = make_heap(arr[1, k]);</span><br><span class="line"></span><br><span class="line">for(i=k+1 to n)&#123;</span><br><span class="line"></span><br><span class="line">         adjust_heap(heep[k],arr[i]);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">return heap[k];</span><br></pre></td></tr></table></figure>
<p><strong>分析</strong>：可以看成三个规则的组合：</p>
<p>1. 新建堆</p>
<p>2. for循环</p>
<p>3. 调整堆</p>
<p>故，用<strong>堆求解TopK</strong>，时间复杂度为：</p>
<p>O(k) + O(n) <em> O(lg(k)) = O(n</em>lg(k))</p>
<p><em>画外音：注意哪些地方用加，哪些地方用乘；哪些地方是n，哪些地方是k。</em></p>
<p><strong>第三大类，递归求解</strong></p>
<p>简单规则和组合规则可以用来求解非递归的算法的时间复杂度。<strong>对于递归的算法，该怎么分析呢？</strong></p>
<p>接下来，通过几个案例，来说明如何通分析递归式，来分析<strong>递归算法</strong>的时间复杂度。</p>
<p><strong>案例一：计算 1到n的和，时间复杂度分析。</strong></p>
<p>如果用<strong>非递归的算法</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">int sum(int n)&#123;</span><br><span class="line"></span><br><span class="line">         int result=0;</span><br><span class="line"></span><br><span class="line">         for(int i=0;i&lt;n;i++)</span><br><span class="line"></span><br><span class="line">                   result += i;</span><br><span class="line"></span><br><span class="line">         return result;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>根据简单规则，for循环，sum的时间复杂度是O(n)。</p>
<p>但如果是<strong>递归算法</strong>，就没有这么直观了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">int sum(int n)&#123;</span><br><span class="line"></span><br><span class="line">         if (n==1) return 1;</span><br><span class="line"></span><br><span class="line">         return n+sum(n-1);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>如何来进行时间复杂度分析呢？</strong></p>
<p>用f(n)来表示数据量为n时，算法的计算次数，很容易知道：</p>
<ul>
<li>当n=1时，sum函数只计算1次</li>
</ul>
<p><em>画外音：if (n==1) return 1;</em></p>
<p>即：</p>
<p>f(1)=1<strong>【式子A】</strong></p>
<p>不难发现，当n不等于1时：</p>
<ul>
<li>f(n)的计算次数，等于f(n-1)的计算次数，再加1次计算</li>
</ul>
<p><em>画外音：return n+sum(n-1);</em></p>
<p>即：</p>
<p>f(n)=f(n-1)+1<strong>【式子B】</strong></p>
<p>【式子B】不断的展开，再配合【式子A】：</p>
<p><em>画外音：这一句话，是分析这个算法的关键。</em></p>
<p>f(n)=f(n-1)+1</p>
<p>f(n-1)=f(n-2)+1</p>
<p>…</p>
<p>f(2)=f(1)+1</p>
<p>f(1)=1</p>
<p>上面共n个等式，左侧和右侧分别相加：</p>
<p>f(n)+f(n-1)+…+f(2)+f(1)</p>
<p>=</p>
<p>[f(n-1)+1]+[f(n-2)+1]+…+[f(1)+1]+[1]</p>
<p><strong>即得到</strong>：</p>
<p>f(n)=n</p>
<p>已经有那么点意思了哈，再来个复杂点的算法。</p>
<p><strong>案例二：二分查找binary_search，时间复杂度分析。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">int BS(int[] arr, int low, int high, int target)&#123;</span><br><span class="line"></span><br><span class="line">         if (low&gt;high) return -1;</span><br><span class="line"></span><br><span class="line">         mid = (low+high)/2;</span><br><span class="line"></span><br><span class="line">         if (arr[mid]== target) return mid;</span><br><span class="line"></span><br><span class="line">         if (arr[mid]&gt; target)</span><br><span class="line"></span><br><span class="line">                  return BS(arr, low, mid-1, target);</span><br><span class="line"></span><br><span class="line">         else</span><br><span class="line"></span><br><span class="line">                  return BS(arr, mid+1, high, target);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>二分查找，单纯从递归算法来分析，怎能知道其时间复杂度是O(lg(n))呢？</strong></p>
<p>仍用f(n)来表示数据量为n时，算法的计算次数，很容易知道：</p>
<ul>
<li>当n=1时，bs函数只计算1次</li>
</ul>
<p><em>画外音：不用纠结是1次还是1.5次，还是2.7次，是一个常数次。</em></p>
<p>即：</p>
<p>f(1)=1<strong>【式子A】</strong></p>
<p>在n很大时，二分会进行一次比较，然后进行左侧或者右侧的递归，以减少一半的数据量：</p>
<ul>
<li>f(n)的计算次数，等于f(n/2)的计算次数，再加1次计算</li>
</ul>
<p><em>画外音：计算arr[mid]&gt;target，再减少一半数据量迭代</em></p>
<p>即：</p>
<p>f(n)=f(n/2)+1<strong>【式子B】</strong></p>
<p>【式子B】不断的展开，</p>
<p>f(n)=f(n/2)+1</p>
<p>f(n/2)=f(n/4)+1</p>
<p>f(n/4)=f(n/8)+1</p>
<p>…</p>
<p>f(n/2^(m-1))=f(n/2^m)+1</p>
<p>上面共m个等式，左侧和右侧分别相加：</p>
<p>f(n)+f(n/2)+…+f(n/2^(m-1))<br>=<br>[f(n/2)+1]+[f(n/4)+1]+…+[f(n/2^m)]+[1]</p>
<p><strong>即得到</strong>：</p>
<p>f(n)=f(n/2^m)+m</p>
<p>再配合【式子A】：</p>
<p>f(1)=1</p>
<p>即，n/2^m=1时, f(n/2^m)=1, 此时m=lg(n), 这一步，这是分析这个算法的关键。</p>
<p>将m=lg(n)带入，<strong>得到</strong>：</p>
<p>f(n)=1+lg(n)</p>
<p><strong>神奇不神奇？</strong></p>
<p>最后，大boss，快速排序递归算法，时间复杂度的分析过程。</p>
<p><strong>案例三：快速排序quick_sort，时间复杂度分析。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">void quick_sort(int[]arr, int low, inthigh)&#123;</span><br><span class="line"></span><br><span class="line">         if (low==high) return;</span><br><span class="line"></span><br><span class="line">         int i = partition(arr, low, high);</span><br><span class="line"></span><br><span class="line">         quick_sort(arr, low, i-1);</span><br><span class="line"></span><br><span class="line">         quick_sort(arr, i+1, high);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>仍用f(n)来表示数据量为n时，算法的计算次数，很容易知道：</p>
<ul>
<li>当n=1时，quick_sort函数只计算1次</li>
</ul>
<p>f(1)=1<strong>【式子A】</strong></p>
<p>在n很大时：</p>
<p>第一步，先做一次partition；</p>
<p>第二步，左半区递归；</p>
<p>第三步，右半区递归；</p>
<p>即：</p>
<p>f(n)=n+f(n/2)+f(n/2)=n+2*f(n/2)<strong>【式子B】</strong></p>
<p><em>画外音：</em></p>
<p><em>(1)partition本质是一个for，计算次数是n；</em></p>
<p><em>(2)二分查找只需要递归一个半区，而快速排序左半区和右半区都要递归，这一点在<strong>分治法</strong>与<strong>减治法</strong>一章节已经详细讲述过；</em></p>
<p>【式子B】不断的展开，</p>
<p>f(n)=n+2*f(n/2)</p>
<p>f(n/2)=n/2+2*f(n/4)</p>
<p>f(n/4)=n/4+2*f(n/8)</p>
<p>…</p>
<p>f(n/2^(m-1))=n/2^(m-1)+2f(n/2^m)</p>
<p>上面共m个等式，逐步带入，于是得到：</p>
<p>f(n)=n+2*f(n/2)</p>
<p>=n+2<em>[n/2+2\</em>f(n/4)]=2n+4*f(n/4)</p>
<p>=2n+4<em>[n/4+2</em>f(n/8)]=3n+8f(n/8)</p>
<p>=…</p>
<p>=m*n+2^m*f(n/2^m)</p>
<p>再配合【式子A】：</p>
<p>f(1)=1</p>
<p>即，n/2^m=1时, f(n/2^m)=1, 此时m=lg(n), 这一步，这是分析这个算法的关键。</p>
<p>将m=lg(n)带入，<strong>得到：</strong></p>
<p>f(n)=lg(n)*n+2^(lg(n))*f(1)=n*lg(n)+n</p>
<p>故，快速排序的时间复杂度是n*lg(n)。</p>
<p><strong>wacalei，有点意思哈！</strong></p>
<p><em>画外音：额，估计83%的同学没有细究看，花5分钟细思上述过程，一定有收获。</em>  </p>
<p><strong>总结</strong></p>
<ul>
<li><p><strong>for循环</strong>的时间复杂度往往是O(n)</p>
</li>
<li><p><strong>树的高度</strong>的时间复杂度往往是O(lg(n))</p>
</li>
<li><p><strong>二分查找</strong>的时间复杂度是O(lg(n))，<strong>快速排序</strong>的时间复杂度n*(lg(n))</p>
</li>
<li><p><strong>递归求解</strong>，未来再问时间复杂度，通杀</p>
</li>
</ul>
<p><strong>知其然，知其所以然。</strong></p>
<p>思路比结论重要。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果你觉得这篇文章对你有用，欢迎赞赏哦~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/wechatpay.png" alt="Felix 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/alipay.png" alt="Felix 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
	
	<div>
  
    <div>
    
        <div style="text-align: center;font-size: 13px;letter-spacing: 10px;user-select: none;margin-top: 50px;color: #bbb;">本文结束啦 <i class="fa fa-star"></i> 感谢您阅读</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/时间复杂度/" rel="tag"><i class="fa fa-tag"></i> 时间复杂度</a>
          
            <a href="/tags/算法/" rel="tag"><i class="fa fa-tag"></i> 算法</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
               <div id="needsharebutton-postbottom">
                 <span class="btn" title="分享">
                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                 </span>
               </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
			
			   <a href="/2018/10/16/Idea开发环境中搭建Maven并且使用Maven打包部署程序/" rel="prev" title="Idea开发环境中搭建Maven并且使用Maven打包部署程序">
			   <i class="fa fa-chevron-left"></i> Idea开发环境中搭建Maven并且使用Maven打包部署程序
			   
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
             
				<a href="/2018/10/10/如何对JPA或者MyBatis进行技术选型/" rel="next" title="如何对JPA或者MyBatis进行技术选型">
				如何对JPA或者MyBatis进行技术选型 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODUyNC8xNTA1Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/">
              <img class="site-author-image" itemprop="image"
                src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg"
                alt="Felix" />
				</a>
            
              <p class="site-author-name" itemprop="name">Felix</p>
              <p class="site-description motion-element" itemprop="description">周宇峰的博客</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">94</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">88</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/542869246" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/zyf542869246" target="_blank" title="Gitee"><i class="fa fa-fw fa-git"></i>Gitee</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://music.163.com/#/user/home?id=343583524" target="_blank" title="网易云音乐"><i class="fa fa-fw fa-music"></i>网易云音乐</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/yu-sui-58/activities" target="_blank" title="知乎"><i class="fa fa-fw fa-globe"></i>知乎</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://zblog.dawnings.top/" title="删库东😎" target="_blank">删库东😎</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ntssl.cn" title="ntssl.cn" target="_blank">ntssl.cn</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.imyzt.top/" title="imyzt" target="_blank">imyzt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.charmsongo.cn/" title="charmsongo" target="_blank">charmsongo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.52share.online" title="HuiProgramer" target="_blank">HuiProgramer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://music.163.com/#/user/home?id=343583524" title="😆 网易云音乐 😆" target="_blank">😆 网易云音乐 😆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhihu.com/people/yu-sui-58/activities" title="😤 知乎 😤" target="_blank">😤 知乎 😤</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/spring-boot.html" title="spring-boot 纯洁的微笑" target="_blank">spring-boot 纯洁的微笑</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python教程 廖雪峰" target="_blank">Python教程 廖雪峰</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="/about" title="关于此博客" target="_blank">关于此博客</a>
                  </li>
                
              </ul>
			  <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
            </div>
          

          
            
          
          <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-tint"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Felix</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">538k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:13</span>
  
  
  <div style="background-image:linear-gradient(90deg,#6dba82 0,#07b39b 15%,#1098ad 30%,#5073b8 44%,#a166ab 58%,#ef4e7b 72%,#f37055 86%,#f79533 100%);background-size:cover;-webkit-background-clip:text;-webkit-text-fill-color:transparent;user-select:none"><i>Tip: 本站电脑访问体验更佳耶&nbsp;<i class="fa fa-angellist" style="display:inline"></i></i></div>
  
</div>


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>





-->



  <span>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></span>



<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，加好友</div>
    </div>
  </div>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  
    <script type="text/javascript">
      window.livereOptions = {
        refer: '2018/10/11/拜托，面试别再问我时间复杂度了！！！/'
      };
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! See more at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see here how to solve it: https://github.com/theme-next/hexo-leancloud-counter-security. \n But you also can use LeanCloud without security, by set \'security\' option to \'false\'.');
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz",
                'X-LC-Key': "xihAA2ETGTdekJFloguCmmgq",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Reddit,Delicious,StumbleUpon,Pinterest,Facebook,GooglePlus,Slashdot,Technorati,Posterous,Tumblr,GoogleBookmarks,Newsvine,Evernote,Friendfeed,Vkontakte,Odnoklassniki,Mailru";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Facebook,Tumblr,Friendfeed";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

  

  

  
  <div class="bg_content">
	<canvas id="canvas"></canvas>
	<canvas id="canvas1"></canvas>
	  <!-- html5-canvas-animation
	  <div class="canvas-wrap">
		<div id="canvas3" class="gradient"></div>
	</div>-->
  </div>
  
  
  
  <!-- 右上角github关注-->
  <div class="forkme">
	<!--<a href="https://github.com/542869246">
	<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://pd2tflnys.bkt.clouddn.com/img/blog/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
	</a>-->
	<a href="https://github.com/542869246" class="github-corner" aria-label="View source on GitHub">
	<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
	<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
	<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
	</svg>
	</a>
	<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  </div>
  
  <!-- 音乐播放器-->
  <link rel="stylesheet" href="/dist/APlayer.min.css">
  <div id="aplayer"></div>
  <script type="text/javascript" src="/dist/APlayer.min.js"></script>
  <script type="text/javascript" src="/dist/music.js"></script>
 
   <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
 <!-- 页面点击汉字 -->
<script type="text/javascript" src="/js/src/hanzi.js"></script>
  
  <!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
<script type="text/javascript" src="/js/src/clipboard-use.js"></script>
<!-- 流星雨-->
<!--<script type="text/javascript" src="/js/src/meteor-rain.js"></script>-->
<!-- 粒子效果-->
<script type="text/javascript" src="/js/src/dynamic_bg.js"></script>

<!-- html5-canvas-animation-->
<!-- Main library
<script src="/js/src/three.min.js"></script> -->
<!-- Helpers
<script src="/js/src/projector.js"></script>
<script src="/js/src/canvas-renderer.js"></script> -->
<!-- Visualitzation adjustments 
<script src="/js/src/3d-lines-animation.js"></script>-->
<!-- Animated background color 
<script src="/js/src/color.js"></script>-->



</body>
</html>
